package com.cgah


class EmailService {
    def mailService;
    def listingService;
    static transactional = true

    // it's better to do this with a view.
    void sendBidSuccessEmail(Bid bidInstance, String listingId) {
        String email = bidInstance.customer?.emailAddress
        String bidAmount = bidInstance.amount
        String bidDateTime = bidInstance.dateTime
        String theListingName = bidInstance.listing?.name//listingService.getListingById(listingId as long)?.name

        if (email) {
            // Get Listing Info
            mailService.sendMail {
                to email
                from "cgah.com"
                subject "Bid Successful"
                body """\
                Good news--You successfully placed a bid on ${theListingName} on ${bidDateTime}!
                The bid amount was ${bidAmount}.
                Have a great day,
                CooCoo Guys
                """\
            }
        }
    }

    // better to do this with a view.
    // Used for Requriement C-3
     void sendListingExpiredEmail(Listing listing) {
        String winnerEmail = listing.winner?.emailAddress
        String listerEmail = listing.seller?.emailAddress
        String winnerName = listing.winner?.username
        String finalBidAmount = listingService.lastBids(listing.id, 1)?.amount
        String listingEndDateTime = listing.endDateTime
         String theListingName = listing?.name
        String listingUrl = "http://localhost:8080/cgah/listing/show/${listing.id}"

        // don't send if there was no winner.
        if (winnerEmail) {
            // Get Listing Info
            mailService.sendMail {
                to winnerEmail
                subject "Listing Closed!"
                body """\
                The listing ${theListingName} was closed on ${listingEndDateTime}!
                The listing was won by ${winnerName}.
                The winning bid was for ${finalBidAmount}.
                You can view the listing here: ${listingUrl}
                Have a great day,
                CooCoo Guys
                """\
            }
        }
    }

    /// Sends email notifications for the victims of the provided listing list.
    void sendListingExpiredNotifications(def listings)
    {
        if(!listings) return;

        for (listing in listings)
        {
            sendListingExpiredEmail(listing)
        }
    }
}
